import 'package:craze/models/index.dart';
import 'package:craze/services/index.dart';
import 'package:craze/stores/index.dart';
import "package:flutter/material.dart";
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:craze/common/index.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:intl/intl.dart';
import 'package:shimmer/shimmer.dart';
import '../san/image_preview_page.dart';

class CommunityView extends StatefulWidget {
  const CommunityView({super.key});

  @override
  State<CommunityView> createState() => _CommunityViewState();
}

class _CommunityViewState extends State<CommunityView> {
  // 获取store
  final UserService _userService = getIt<UserService>();
  final TeamStore _teamStore = getIt<TeamStore>();
  final ShareStore _shareStore = getIt<ShareStore>();
  final AuthStore _authStore = getIt<AuthStore>();

  // 数据列表
  List<UserModel> _users = [];
  bool _isLoadingUsers = true;

  // 记录关注状态
  final Map<String, bool> _followStatus = {};

  // 记录收藏状态
  final Map<String, bool> _collectStatus = {};

  // 滚动控制器
  final ScrollController _friendScrollController = ScrollController();

  @override
  void initState() {
    super.initState();

    // 确保页面先渲染完成，再加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadData();
      // 启动自动滚动
      _startAutoScroll();
    });
  }

  @override
  void dispose() {
    _friendScrollController.dispose();
    super.dispose();
  }

  // 自动滚动方法
  void _startAutoScroll() {
    Future.delayed(const Duration(milliseconds: 50), () {
      if (!mounted) return;

      // 好友列表滚动
      if (_friendScrollController.hasClients) {
        double newPosition = _friendScrollController.offset + 0.6;
        // 如果滚动到最后，就从头开始
        if (newPosition >= _friendScrollController.position.maxScrollExtent) {
          newPosition = 0;
        }
        _friendScrollController.jumpTo(newPosition);
      }

      // 继续滚动
      _startAutoScroll();
    });
  }

  // 加载数据
  Future<void> _loadData() async {
    setState(() {
      _isLoadingUsers = true;
    });

    // 加载团队和分享数据前设置 isLoading 状态
    _teamStore.isLoading = true;
    _shareStore.isLoading = true;

    // 添加足够长的延迟来观察用户列表的骨架屏
    await Future.delayed(const Duration(seconds: 2));

    // 获取用户列表
    _users = _userService.getAllUsers();

    // 初始化关注状态
    _initFollowStatus();

    // 更新用户列表状态
    setState(() {
      _isLoadingUsers = false;
    });

    // 为团队列表添加延迟
    await Future.delayed(const Duration(seconds: 2));

    // 加载团队数据（内部会更新自己的isLoading状态）
    await _teamStore.loadTeams();

    // 为分享列表添加延迟
    await Future.delayed(const Duration(seconds: 2));

    // 加载分享数据
    await _shareStore.loadShares();

    // 初始化收藏状态
    _initCollectStatus();
  }

  // 初始化关注状态
  void _initFollowStatus() {
    if (_authStore.isLoggedIn && _authStore.currentUser != null) {
      for (final user in _users) {
        _followStatus[user.id] = _authStore.currentUser!.followingIds.contains(
          user.id,
        );
      }
    }
  }

  // 初始化收藏状态
  void _initCollectStatus() {
    _collectStatus.clear();
    if (_authStore.isLoggedIn && _authStore.currentUser != null) {
      final userId = _authStore.currentUser!.id;
      final collectedShares = CollectionService().getUserCollectedShares(
        userId,
      );
      for (final share in _shareStore.shares) {
        _collectStatus[share.id] = collectedShares.any((s) => s.id == share.id);
      }
    }
  }

  // 显示登录提示对话框
  void _showLoginDialog() {
    LoginDialog.show(
      context,
      title: 'Login',
      description: 'Please login to use this feature',
    );
  }

  // 关注/取消关注用户
  Future<void> _toggleFollowUser(UserModel user) async {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) {
      _showLoginDialog();
      return;
    }

    final currentUserId = _authStore.currentUser!.id;
    final targetUserId = user.id;

    // 判断当前是否已关注
    bool isFollowed = _followStatus[targetUserId] ?? false;

    try {
      setState(() {
        // 立即更新UI状态，提供即时反馈
        _followStatus[targetUserId] = !isFollowed;
      });

      if (isFollowed) {
        // 取消关注
        await _userService.unfollowUser(currentUserId, targetUserId);
      } else {
        // 关注
        await _userService.followUser(currentUserId, targetUserId);
      }

      // 刷新登录用户信息以获取最新的关注列表
      _authStore.currentUser = _userService.getUserById(currentUserId);
    } catch (e) {
      // 如果出错，恢复原状态
      setState(() {
        _followStatus[targetUserId] = isFollowed;
      });

      // 显示错误提示
      if (mounted) {
        MyToast.showError(context, e.toString());
      }
    }
  }

  // 切换分享收藏状态
  Future<void> _toggleCollect(String postId) async {
    if (!_authStore.isLoggedIn) {
      _showLoginDialog();
      return;
    }

    // 当前收藏状态
    final isCollected = _collectStatus[postId] ?? false;

    try {
      // 立即更新本地状态，提供即时反馈
      setState(() {
        _collectStatus[postId] = !isCollected;
      });

      // 调用API切换收藏状态
      await _shareStore.toggleShareCollected(postId);
    } catch (e) {
      // 如果出错，恢复原状态
      setState(() {
        _collectStatus[postId] = isCollected;
      });

      // 显示错误提示
      if (mounted) {
        MyToast.showError(context, e.toString());
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: 1.sh,
        width: 1.sw,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                // 标题
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Text(
                    'Friend Recommendation',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 22.sp,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      fontWeight: FontWeight.w400,
                      height: 1.36,
                    ),
                  ),
                ),
                SizedBox(height: 16.h),
                // 推荐好友列表
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 推荐好友列表
                    SizedBox(
                      height: 140.h,
                      child:
                          _isLoadingUsers
                              ? _buildFriendShimmer()
                              : ListView.builder(
                                controller: _friendScrollController,
                                scrollDirection: Axis.horizontal,
                                physics:
                                    const NeverScrollableScrollPhysics(), // 禁止手动滚动
                                itemCount: _users.length * 2, // 重复显示两次实现无限循环效果
                                itemBuilder: (context, index) {
                                  final user =
                                      _users[index %
                                          _users.length]; // 使用取模操作循环用户列表
                                  return Padding(
                                    padding: EdgeInsets.only(right: 12.w),
                                    child: FriendCard(
                                      user: user,
                                      onFollow: () => _toggleFollowUser(user),
                                      isFollowed:
                                          _followStatus[user.id] ?? false,
                                      isLoggedIn: _authStore.isLoggedIn,
                                    ),
                                  );
                                },
                              ),
                    ),
                  ],
                ),

                SizedBox(height: 28.h),

                // 标题
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Text(
                    'Diving Team',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 22.sp,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      fontWeight: FontWeight.w400,
                      height: 1.36,
                    ),
                  ),
                ),

                SizedBox(height: 16.h),

                // 推荐团队列表
                Padding(
                  padding: EdgeInsets.only(left: 20.w),
                  child: SizedBox(
                    height: 148.h,
                    width: double.infinity,
                    child: Observer(
                      builder: (_) {
                        if (_teamStore.isLoading) {
                          return _buildTeamShimmer();
                        }

                        if (_teamStore.teams.isEmpty) {
                          return Center(
                            child: Text(
                              'No teams available',
                              style: TextStyle(color: Colors.white),
                            ),
                          );
                        }

                        return ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: _teamStore.teams.length + 1, // +1 为创建团队卡片
                          itemBuilder: (context, index) {
                            // 第一个是创建团队卡片
                            if (index == 0) {
                              return Padding(
                                padding: EdgeInsets.only(right: 12.w),
                                child: GestureDetector(
                                  onTap: () async {
                                    if (!_authStore.isLoggedIn) {
                                      _showLoginDialog();
                                      return;
                                    }
                                    final result = await GoRouter.of(
                                      context,
                                    ).push(AppRouter.createTeam);
                                    if (result == true) {
                                      await _teamStore.loadTeams();
                                      setState(() {});
                                    }
                                  },
                                  child: AspectRatio(
                                    aspectRatio: 156 / 148,
                                    child: Image.asset(
                                      MyImages.createTeam,
                                      fit: BoxFit.contain,
                                    ),
                                  ),
                                ),
                              );
                            }

                            // 获取实际团队数据
                            final team = _teamStore.teams[index - 1];
                            // 第一个团队使用teamBg背景，其余使用teamCommonBg背景
                            final bgImage =
                                index == 1
                                    ? MyImages.teamBg
                                    : MyImages.teamCommonBg;
                            return Padding(
                              padding: EdgeInsets.only(right: 12.w),
                              child: _createTeamCard(team, bgImage),
                            );
                          },
                        );
                      },
                    ),
                  ),
                ),

                SizedBox(height: 28.h),

                // 标题
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Row(
                    children: [
                      Text(
                        'Diving Sharing',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 22.sp,
                          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          fontWeight: FontWeight.w400,
                          height: 1.36,
                        ),
                      ),
                      const Spacer(),
                      GestureDetector(
                        onTap: () {
                          if (!_authStore.isLoggedIn) {
                            _showLoginDialog();
                            return;
                          }
                          GoRouter.of(context).push(AppRouter.uploadShare);
                        },
                        child: Row(
                          children: [
                            Icon(
                              MyIcons.iconEdit,
                              color: Colors.white,
                              size: 24.sp,
                            ),
                            SizedBox(width: 4.w),
                            Text(
                              'release',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 12.sp,
                                fontFamily:
                                    GoogleFonts.mochiyPopOne().fontFamily,
                                fontWeight: FontWeight.w400,
                                height: 1,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 20.h),

                // 分享列表
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Observer(
                    builder: (_) {
                      if (_shareStore.isLoading) {
                        return _buildShareShimmer();
                      }

                      if (_shareStore.shares.isEmpty) {
                        return Center(
                          child: Text(
                            'No shares available',
                            style: TextStyle(color: Colors.white),
                          ),
                        );
                      }

                      return Column(
                        children: [
                          ...List.generate(
                            _shareStore.shares.length,
                            (index) => Padding(
                              padding: EdgeInsets.only(bottom: 20.h),
                              child: _buildSharePostCard(
                                _shareStore.shares[index],
                              ),
                            ),
                          ),
                        ],
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 好友列表骨架屏
  Widget _buildFriendShimmer() {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: 5,
      itemBuilder: (context, index) {
        return Padding(
          padding: EdgeInsets.only(right: 12.w),
          child: Shimmer.fromColors(
            baseColor: const Color(0xFF1E1F31),
            highlightColor: const Color(0xFF353656),
            child: Container(
              width: 114.w,
              height: 140.h,
              decoration: BoxDecoration(
                color: const Color(0xFF1E1F31),
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // Avatar placeholder
                  Container(
                    width: 54.w,
                    height: 54.w,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      shape: BoxShape.circle,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  // Name placeholder
                  Container(width: 80.w, height: 12.h, color: Colors.white),
                  SizedBox(height: 8.h),
                  // Button placeholder
                  Container(
                    width: 60.w,
                    height: 24.h,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  // 团队列表骨架屏
  Widget _buildTeamShimmer() {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: 3,
      itemBuilder: (context, index) {
        return Padding(
          padding: EdgeInsets.only(right: 12.w),
          child: Shimmer.fromColors(
            baseColor: const Color(0xFF1E1F31),
            highlightColor: const Color(0xFF353656),
            child: Container(
              width: 206.w,
              height: 148.h,
              decoration: BoxDecoration(
                color: const Color(0xFF1E1F31),
                borderRadius: BorderRadius.circular(16.r),
              ),
            ),
          ),
        );
      },
    );
  }

  // 分享列表骨架屏
  Widget _buildShareShimmer() {
    return Column(
      children: List.generate(
        3,
        (index) => Padding(
          padding: EdgeInsets.only(bottom: 20.h),
          child: Shimmer.fromColors(
            baseColor: const Color(0xFF1E1F31),
            highlightColor: const Color(0xFF353656),
            child: Container(
              width: 374.w,
              height: 250.h,
              decoration: BoxDecoration(
                color: const Color(0xFF1E1F31),
                borderRadius: BorderRadius.circular(16.r),
              ),
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 14.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 顶部用户信息占位
                  Row(
                    children: [
                      Container(
                        width: 44.w,
                        height: 44.w,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          shape: BoxShape.circle,
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Container(
                        width: 100.w,
                        height: 16.h,
                        color: Colors.white,
                      ),
                    ],
                  ),
                  SizedBox(height: 12.h),

                  // 描述文字占位
                  Container(
                    width: double.infinity,
                    height: 40.h,
                    color: Colors.white,
                  ),
                  SizedBox(height: 12.h),

                  // 图片占位
                  Container(
                    width: double.infinity,
                    height: 113.h,
                    color: Colors.white,
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSharePostCard(SharePostModel post) {
    // 获取发布用户信息
    UserModel? user = _userService.getUserById(post.userId);
    String userName = user?.name ?? "Unknown";
    String userAvatar = user?.avatar ?? MyImages.touxiang1;

    // 获取查看者头像列表（最多4个）
    List<String> viewerAvatars = [];
    if (post.viewerIds.isNotEmpty) {
      for (int i = 0; i < post.viewerIds.length && i < 4; i++) {
        UserModel? viewer = _userService.getUserById(post.viewerIds[i]);
        if (viewer != null && viewer.avatar.isNotEmpty) {
          viewerAvatars.add(viewer.avatar);
        } else {
          viewerAvatars.add(MyImages.touxiang1); // 默认头像
        }
      }
    }

    // 检查当前登录用户是否已关注分享发布者
    bool isFollowed = false;
    if (_authStore.isLoggedIn &&
        _authStore.currentUser != null &&
        user != null) {
      isFollowed = _followStatus[user.id] ?? false;
    }

    // 获取收藏状态（未登录时一律为未收藏）
    final isCollected =
        _authStore.isLoggedIn ? (_collectStatus[post.id] ?? false) : false;

    return GestureDetector(
      onTap: () {
        GoRouter.of(context).push('/share-detail/${post.id}');
      },
      child: Container(
        width: 374.w,
        decoration: BoxDecoration(
          color: Colors.white.withAlpha(25),
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 14.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 第一排：头像、用户名、关注按钮、收藏图标
              Row(
                children: [
                  // 头像
                  GestureDetector(
                    onTap: () {
                      GoRouter.of(context).push(
                        AppRouter.otherProfile,
                        extra: {'userId': user?.id},
                      );
                    },
                    child: CircleAvatar(
                      radius: 22.r,
                      backgroundImage: AssetImage(userAvatar),
                    ),
                  ),
                  SizedBox(width: 8.w),
                  // 用户名
                  Text(
                    userName,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w400,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    ),
                  ),
                  Spacer(),
                  // 时间 （格式化年月日）
                  Text(
                    DateFormat('yyyy-MM-dd').format(post.createdAt),
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12.sp,
                      fontFamily: GoogleFonts.inter().fontFamily,
                    ),
                  ),

                  // // 关注按钮
                  // GestureDetector(
                  //   onTap: () {
                  //     if (user != null) {
                  //       _toggleFollowUser(user);
                  //     }
                  //   },
                  //   child: Container(
                  //     padding: EdgeInsets.symmetric(
                  //       horizontal: 6.w,
                  //       vertical: 4.h,
                  //     ),
                  //     decoration: BoxDecoration(
                  //       color: isFollowed ? Colors.grey : Colors.blue,
                  //       borderRadius: BorderRadius.circular(12.r),
                  //     ),
                  //     child: Row(
                  //       children: [
                  //         Icon(
                  //           isFollowed ? Icons.check : MyIcons.iconAdd,
                  //           color: Colors.white,
                  //           size: 12.sp,
                  //         ),
                  //         SizedBox(width: 4.w),
                  //         Text(
                  //           isFollowed ? 'followed' : 'follow',
                  //           style: TextStyle(
                  //             color: Colors.white,
                  //             fontSize: 13.sp,
                  //             fontWeight: FontWeight.w700,
                  //             fontFamily: GoogleFonts.inter().fontFamily,
                  //           ),
                  //         ),
                  //       ],
                  //     ),
                  //   ),
                  // ),
                  // const Spacer(),
                  // // 收藏图标（无动画）
                  // GestureDetector(
                  //   onTap: () => _toggleCollect(post.id),
                  //   child: Container(
                  //     padding: EdgeInsets.all(8.r),
                  //     decoration: BoxDecoration(
                  //       color: MyColors.iconDark,
                  //       shape: BoxShape.circle,
                  //     ),
                  //     child: Icon(
                  //       isCollected
                  //           ? MyIcons.iconCollectFill
                  //           : MyIcons.iconCollect,
                  //       color: isCollected ? Colors.red : Colors.white,
                  //       size: 24.sp,
                  //     ),
                  //   ),
                  // ),
                ],
              ),
              SizedBox(height: 12.h),

              // 第二排：分享详情文字
              Text(
                post.description,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  height: 1.5,
                  fontFamily: GoogleFonts.inter().fontFamily,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              SizedBox(height: 12.h),

              // 第三排：图片
              SizedBox(
                height: 113.h,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: List.generate(
                    post.imageUrls.length > 3 ? 3 : post.imageUrls.length,
                    (index) => Hero(
                      tag: '${post.id}_image_$index',
                      child: GestureDetector(
                        onTap: () {
                          // 点击图片，跳转到预览页
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder:
                                  (context) => ImagePreviewPage(
                                    imagePath: post.imageUrls[index],
                                    isAsset: post.imageUrls[index].startsWith(
                                      'assets/',
                                    ),
                                  ),
                            ),
                          );
                        },
                        child: Container(
                          width: 113.w,
                          height: 113.h,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(12.r),
                            image: DecorationImage(
                              image: AssetImage(post.imageUrls[index]),
                              fit: BoxFit.cover,
                              onError:
                                  (exception, stackTrace) =>
                                      const AssetImage(MyImages.startBg),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(height: 12.h),

              // 第四排：已浏览头像和举报按钮
              Row(
                children: [
                  if (viewerAvatars.isEmpty)
                    // 没有查看者的情况
                    Expanded(
                      child: Text(
                        'No views yet',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 11.sp,
                          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          fontWeight: FontWeight.w400,
                          height: 1.36,
                        ),
                      ),
                    )
                  else
                    // 有查看者的情况
                    Row(
                      children: [
                        // 已浏览头像
                        SizedBox(
                          width: 120.w,
                          height: 37.h,
                          child: Stack(
                            children: List.generate(
                              viewerAvatars.length,
                              (index) => Positioned(
                                left: index * 25.w,
                                child: Container(
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color: MyColors.blue,
                                      width: 1.w,
                                    ),
                                  ),
                                  child: CircleAvatar(
                                    radius: 18.r,
                                    backgroundImage: AssetImage(
                                      viewerAvatars[index],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 4.w),
                        // Already viewed 文字
                        Text(
                          'Already viewed',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 11.sp,
                            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                            fontWeight: FontWeight.w400,
                            height: 1.36,
                          ),
                        ),
                      ],
                    ),

                  const Spacer(),

                  // 举报按钮
                  GestureDetector(
                    onTap: () {
                      ReportDialog.show(
                        context,
                        title: 'Report',
                        description:
                            'Please select a reason for reporting this post.',
                        onSubmit: (type) async {
                          MyToast.showSuccess(context, 'Report successful');
                          await getIt<ShareService>().deleteSharePost(post.id);
                          // 重新加载数据
                          await _shareStore.loadShares();
                        },
                      );
                    },
                    child: Container(
                      padding: EdgeInsets.all(8.r),
                      decoration: BoxDecoration(
                        color: MyColors.iconDark,
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        MyIcons.iconReport,
                        color: Colors.white,
                        size: 20.sp,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _createTeamCard(TeamModel team, String backgroundImage) {
    // 获取发起者信息
    final initiator = _userService.getUserById(team.initiatorId);
    final initiatorName = initiator?.name ?? "Unknown";

    final dateStr = "${team.departureDate.month}/${team.departureDate.day}";

    // 获取成员头像列表
    List<String> memberAvatars = [];
    for (String memberId in team.memberIds) {
      final member = _userService.getUserById(memberId);
      if (member != null && member.avatar.isNotEmpty) {
        memberAvatars.add(member.avatar);
      } else {
        memberAvatars.add(MyImages.touxiang1); // 默认头像
      }
    }

    return GestureDetector(
      onTap: () {
        _teamStore.selectTeam(team.id);
        GoRouter.of(context).push(AppRouter.team);
      },
      child: Container(
        width: 206.w,
        height: 148.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16.r),
          image: DecorationImage(
            image: AssetImage(backgroundImage),
            fit: BoxFit.fill,
          ),
        ),
        child: Container(
          padding: EdgeInsets.only(left: 16.w, top: 16.h),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.r),
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Colors.transparent, Colors.black.withOpacity(0.7)],
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 团队信息
              Text(
                'Initiator: $initiatorName',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontFamily: GoogleFonts.inter().fontFamily,
                  fontWeight: FontWeight.w700,
                ),
              ),
              SizedBox(height: 4.h),
              Text(
                'Departure Date: $dateStr',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontFamily: GoogleFonts.inter().fontFamily,
                  fontWeight: FontWeight.w700,
                ),
              ),
              SizedBox(height: 4.h),
              Text(
                'Number Of People: ${team.memberIds.length}/${team.maxMembers}',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontFamily: GoogleFonts.inter().fontFamily,
                  fontWeight: FontWeight.w700,
                ),
              ),
              const Spacer(),
              // 成员头像列表
              Row(
                children: [
                  // 已加入的成员头像
                  ...List.generate(
                    memberAvatars.length > team.maxMembers
                        ? team.maxMembers
                        : memberAvatars.length,
                    (index) {
                      return Padding(
                        padding: EdgeInsets.only(right: 6.w),
                        child: CircleAvatar(
                          radius: 12.r,
                          backgroundImage: AssetImage(memberAvatars[index]),
                        ),
                      );
                    },
                  ),
                  // 剩余的加号按钮
                  ...List.generate(team.maxMembers - memberAvatars.length, (
                    index,
                  ) {
                    return Padding(
                      padding: EdgeInsets.only(right: 6.w),
                      child: CircleAvatar(
                        radius: 12.r,
                        backgroundColor: Colors.black38,
                        child: Icon(Icons.add, color: Colors.white, size: 20.r),
                      ),
                    );
                  }),
                ],
              ),
              SizedBox(height: 8.h),
              // 团队名称
              Text(
                team.name,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w700,
                  fontFamily: GoogleFonts.inter().fontFamily,
                ),
                overflow: TextOverflow.ellipsis,
              ),
              const Spacer(),
            ],
          ),
        ),
      ),
    );
  }
}

// Friend card widget
class FriendCard extends StatelessWidget {
  final UserModel user;
  final VoidCallback onFollow;
  final bool isLoggedIn;
  final bool isFollowed;

  const FriendCard({
    super.key,
    required this.user,
    required this.onFollow,
    required this.isLoggedIn,
    required this.isFollowed,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 114.w,
      height: 140.h,
      decoration: BoxDecoration(
        color: Colors.white.withAlpha(25),
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Avatar
          GestureDetector(
            onTap: () {
              GoRouter.of(
                context,
              ).push(AppRouter.otherProfile, extra: {'userId': user.id});
            },
            child: Container(
              width: 54.w,
              height: 54.w,
              decoration: BoxDecoration(shape: BoxShape.circle),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(32.r),
                child: Image.asset(
                  user.avatar.isNotEmpty ? user.avatar : MyImages.touxiang1,
                  fit: BoxFit.cover,
                  errorBuilder:
                      (context, error, stackTrace) => Container(
                        color: Colors.grey[300],
                        child: Icon(
                          Icons.person,
                          size: 40.sp,
                          color: Colors.grey[600],
                        ),
                      ),
                ),
              ),
            ),
          ),
          SizedBox(height: 8.h),
          // Name
          Text(
            user.name,
            style: TextStyle(
              color: Colors.white,
              fontSize: 12.sp,
              fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
              fontWeight: FontWeight.w400,
              height: 1.36,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          SizedBox(height: 8.h),
          // Follow button
          GestureDetector(
            onTap: onFollow,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 6.h),
              decoration: BoxDecoration(
                color: isFollowed ? Colors.grey : Colors.blue,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Text(
                isFollowed ? 'followed' : 'follow',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w600,
                  fontFamily: GoogleFonts.inter().fontFamily,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
